using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Serialization;
using WindowsPhoneEssentials.Abstractions;

namespace WindowsPhoneEssentials.Storage
{
    public class PersistentStore : IPersistentStore
    {
        private readonly IIsolatedStorageFileFactory isolatedStorageFileFactory;
        private const string StoreKey = "WindowsPhoneEssentials.Storage.PersistentStoreFiles";

        public PersistentStore()
        {
            isolatedStorageFileFactory = new IsolatedStorageFileFactory();
        }

        public PersistentStore(IIsolatedStorageFileFactory isolatedStorageFileFactory)
        {
            this.isolatedStorageFileFactory = isolatedStorageFileFactory;
        }

        private IEnumerable<string> FileList
        {
            get
            {
                using (var store = isolatedStorageFileFactory.GetUserStoreForApplication())
                {
                    if (store.FileExists(StoreKey))
                    {
                        using (var stream = store.OpenFile(StoreKey, FileMode.Open))
                        {
                            return new List<string>(SilverlightSerializer.Deserialize<string[]>(stream));
                        }
                    }

                    return new List<string>();
                }
            }
        }

        private void AddFile(string file)
        {
            var files = FileList.Concat(new[] { file }).ToArray();
            using (var store = isolatedStorageFileFactory.GetUserStoreForApplication())
            {
                using (var stream = store.OpenFile(StoreKey, FileMode.Create))
                {
                    SilverlightSerializer.Serialize(files, stream);
                }
            }
        }

        private void RemoveFile(string file)
        {
            var files = FileList.Where(f => f != file).ToArray();
            using (var store = isolatedStorageFileFactory.GetUserStoreForApplication())
            {
                if (!store.FileExists(StoreKey)) return;

                using (var stream = store.OpenFile(StoreKey, FileMode.Create))
                {
                    SilverlightSerializer.Serialize(files, stream);
                }
            }
        }

        public void Save<T>(string key, T value) where T : class
        {
            using (var store = isolatedStorageFileFactory.GetUserStoreForApplication())
            {
                using (var stream = store.OpenFile(GetFileName(key), FileMode.Create))
                {
                    SilverlightSerializer.Serialize(value, stream);
                }
            }

            if (!FileList.Contains(key))
            {
                AddFile(key);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns>null if not found, otherwise saved value</returns>
        public T Load<T>(string key) where T : class
        {
            if (Contains(key))
            {
                using (var store = isolatedStorageFileFactory.GetUserStoreForApplication())
                {
                    using (var stream = store.OpenFile(GetFileName(key), FileMode.OpenOrCreate))
                    {
                        if (stream.Length > 0)
                        {
                            return SilverlightSerializer.Deserialize<T>(stream);
                        }
                    }
                }
            }

            return null;
        }

        public bool Contains(string key)
        {
            return FileList.Contains(key);
        }

        public void Remove(string key)
        {
            RemoveFile(key);
            using (var store = isolatedStorageFileFactory.GetUserStoreForApplication())
            {
                foreach (var file in store.GetFileNames(GetFileName(key)))
                {
                    store.DeleteFile(file);
                }
            }
        }

        private static string GetFileName(string key)
        {
            return string.Format("{0}.{1}", StoreKey, key);
        }
    }
}